package org.linlinjava.litemall.core.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

public class CafeImageScraper {
    public static void main(String[] args) throws IOException {
        String url = " https://stocksnap.io/";
        String saveFolder = "/Library/yliyun_java/爬取图片"; // 更改为您想要保存图片的目录路径
        File folder = new File(saveFolder);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        Document doc = Jsoup.connect(url).get();
        Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
        for (Element image : images) {
            String imageUrl = image.attr("src");
            String fileName = UUID.randomUUID().toString() + ".jpg";
            saveImage(imageUrl, saveFolder + "/" + fileName);
        }
    }

    private static void saveImage(String imageUrl, String fileName) throws IOException {
        URL url = new URL(imageUrl);
        BufferedInputStream in = new BufferedInputStream(url.openStream());
        FileOutputStream out = new FileOutputStream(new File(fileName));
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = in.read(buffer, 0, 1024)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        in.close();
        System.out.println("Image saved as: " + fileName);
    }
}
